const Router = require('koa-router')
const router = new Router()
const mongoose = require('mongoose')
const COS = require('cos-nodejs-sdk-v5');
const fs = require('fs')
const path  = require('path')
const uuid  = require('uuid')



const cos = new COS({
  SecretId: 'AKIDPqEWku043wjv12wkS4c3Uq8LSUQG0fEh',
  SecretKey: 'RuKf4b3SlykWCnIi4LyY4W0Pk0BIMLF7'
})


router.get('/', async (ctx) => {
  ctx.body = '用户操作首页'
})
// -- 导入用户的所有信息
router.get('/insertAllUserInFo',  async (ctx) => {
  // 1. 导入User 2. 使用User.save()方法
  // 读取文件的信息 fs.readFile() 写入信息
  fs.readFile('./data_json/user.json', 'utf8', (err, data) => {
    if (err) return '数据导入失败'
    data = JSON.parse(data)
    const User = mongoose.model('User')
    let saveCount = 0
    data.RECORDS.map((item) => {
      let newUser = new User(item)
      newUser.save().then(res => {
        saveCount++
        console.log('数据导入成功' + saveCount);
      }).catch(err => {
        console.log(err, 'err');
        console.log('数据导入失败');
      })
    })
    ctx.body = '开始导入数据'
  })
})
// -- 注册接口
router.post('/register', async (ctx) => {
  const User = mongoose.model('User')
  let newUser = new User(ctx.request.body)
  let userName = ctx.request.body.userName
  try {
    // 拿着这个用户名去数据库里面查找，如果存在这样的用户名，就报错
    let user = await User.findOne({ userName: userName }).exec()
    console.log(user, 'user');
    if (user) {
      ctx.body = {
        data: {
          code: 500,
          message: '用户名已经存在',
        },
      }
      return
    }
    let res = await newUser.save()
    console.log(res,'我是注册后的res信息');
    ctx.body = {
      data: {
        code: 200,
        message: res,
      },
    }
  } catch (error) {
    ctx.body = {
      data: {
        code: 500,
        message: '注册失败',
      },
    }
  }
})

// -- 登录接口
router.post('/login', async (ctx) => {
  let userInfo = ctx.request.body
  let userName = userInfo.userName
  let passWord = userInfo.passWord
  const User = mongoose.model('User')
  await User.findOne({ userName: userName })
    .exec()
    .then(async (res) => {
      console.log(res);
      if (res) {
        // 这里传入了{}也是欧克的
        let newUser = new User()
        // res.passWord是查到的密码
        try {
          let final = await newUser.comparePassword(passWord, res.passWord)
          console.log(res, 'res的值');
          // final - false 就是密码错误
          final
            ? (ctx.body = {
                code: 200,
                message: '用户登录成功',
                data: {
                  userName: res.userName,
                  avatarUrl: res.avatarUrl,
                  _id: res._id
                },
              })
            : (ctx.body = {
                code: 500,
                message: '用户密码错误',
                data: userInfo,
              })
        } catch (error) {
          ctx.body = {
            code: 500,
            message: error,
          }
        }
      } else {
        ctx.body = {
          code: 500,
          message: '用户不存在', // 没有result
        }
      }
    })
    .catch((error) => {
      ctx.body = {
        msg: 500,
        message: error,
      }
    })
})

// -- 修改昵称的接口
router.post('/updateName', async (ctx) => {
  let userName = ctx.request.body.userName
  let _id = ctx.request.body._id
  const User = mongoose.model('User')
  try {
    let user = await User.findOne({_id: _id})
    if (!user) {
      console.log('没有该用户');
      return ctx.body = {
        code: 404,
        message: '不存在该用户', // 没有result
      }
    } else {
      user.userName = userName
      const res = await user.save()
      ctx.body = {
        code: 200,
        data: {
          message: res
        }
      }
    }
  } catch (error) {
    console.log('保存失败');
    ctx.body = {
      code: 500,
      message: error, // 没有result
    }
  }
})

// -- 修改密码的接口
router.post('/updatePassword', async (ctx) => {
  let passWord = ctx.request.body.passWord
  let _id = ctx.request.body._id
  const User = mongoose.model('User')
  try {
    let user = await User.findOne({_id: _id})
    if (!user) {
      console.log('没有该用户');
      return ctx.body = {
        code: 404,
        message: '不存在该用户', // 没有result
      }
    } else {
      user.passWord = passWord
      const res = await user.save()
      console.log('保存密码成功');
      ctx.body = {
        code: 200,
        data: {
          message: res
        }
      }
    }
  } catch (error) {
    console.log('保存密码失败');
    ctx.body = {
      code: 500,
      message: error, // 没有result
    }
  }
})

// -- 修改头像的接口
router.put('/updatePhoto/:id', async (ctx) => {
  let files = ctx.request.files.files
  let id = ctx.params.id
  const User = mongoose.model('User')
  try {
    // 存储文件到本地磁盘或者云存储服务
    const fileUrl = await saveFileAndGetUrl(files);
    // 存储文件到数据库
    let user = await User.findOneAndUpdate(
      { _id: id }, 
      { avatarUrl: fileUrl }, 
      { new: true }
    )
    console.log('更新头像成功了');
    ctx.body = {
      code: 200,
      message: '更新头像成功',
      data: {
        avatarUrl: user.avatarUrl,
        userName: user.userName,
        passWord: user.passWord,
        _id: user._id
      }
    }
  } catch (error) {
    console.log(error,'更新头像失败了');
    ctx.body = {
      code: 500,
      message: error, // 没有result
    }
  }
})
function saveFileAndGetUrl(file) {
  return new Promise((resolve, reject) => {
    try {
      // 后缀
      let extname
      if (file.mimetype === 'image/png') {
        extname = '.png'
      }
      // uuid.v4() =》 返回唯一的标识 + 后缀
      const filename = uuid.v4() + extname
      // 拼接上名字 放到uploads文件夹
      const key = `uploads/${filename}`
      console.log('我是key');
      cos.sliceUploadFile({
        Bucket: 'graduate-1309613071',
        Region: 'ap-shanghai',
        Key: key,
        FilePath: file.filepath
      }, function (err, data) {
        if (err) {
          console.log('上传腾讯云失败了');
          reject(err)
        } else {
          console.log('上传腾讯云成功了');
          resolve(`https://${data.Location}`)
        }
      })
    } catch (error) {
      console.log('调用api出错', error);
    }
  })
}
module.exports = router
